package com.ulook.planetmanager.widget;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.util.AttributeSet;
import android.view.LayoutInflater;
import android.widget.GridLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.Nullable;

import com.qmuiteam.qmui.widget.QMUIFloatLayout;
import com.qmuiteam.qmui.widget.QMUIRadiusImageView2;
import com.qmuiteam.qmui.widget.roundwidget.QMUIRoundButton;
import com.ulook.planetmanager.R;
import com.ulook.planetmanager.base.WidgetData;
import com.ulook.planetmanager.common.AppServer;
import com.ulook.planetmanager.model.TArtPic;
import com.ulook.planetmanager.model.VArticlePreInfo;
import com.ulook.planetmanager.ui.home.user.UserDetailActivity;
import com.ulook.planetmanager.util.ThrowException;
import com.ulook.planetmanager.util.json.JacksonUtil;
import com.ulook.planetmanager.util.net.AsynRequestUtil;
import com.ulook.planetmanager.util.net.OkHttpException;
import com.ulook.planetmanager.util.net.RequestParams;
import com.ulook.planetmanager.util.net.ResponseCallback;


import java.util.List;

/**
 * 描述：
 *
 * @author L1998
 * @data 2021/4/16
 */
public class ArticleView extends LinearLayout implements WidgetData<VArticlePreInfo> {

    private Context context;
    private VArticlePreInfo articlePreInfo;
    private int currUserID;
    private int imageWidth;

    private QMUIRadiusImageView2 userHeadImg;
    private QMUIFloatLayout imageLayout;

    public ArticleView(Context context) {
        super(context);
        initArticleView(context);
    }

    public ArticleView(Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        initArticleView(context);
    }

    public ArticleView(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        initArticleView(context);
    }

    /**
     * 初始化组件
     * @param context
     */
    private void initArticleView(Context context){
        this.context = context;
        LayoutInflater.from(context).inflate(R.layout.widget_article_view, this, true);

        userHeadImg = findViewById(R.id.w_art_author_img);
        imageLayout = findViewById(R.id.w_art_image_layout);

    }

    /**
     * 设置帖子信息
     */
    @Override
    public void setWidgetData(VArticlePreInfo value) {
        setWidgetData(value, 0);
    }

    /**
     * 设置帖子信息
     */
    @Override
    public void setWidgetData(VArticlePreInfo articlePreInfo, int currUserID){
        this.articlePreInfo = articlePreInfo;
        this.currUserID = currUserID;

        TextView authorName = findViewById(R.id.w_art_author_name_text);
        if(articlePreInfo.getName() != null){
            authorName.setText(articlePreInfo.getName());
        }
        TextView pubTime = findViewById(R.id.w_art_pub_time_text);
        if(articlePreInfo.getPubtime() != null){
            pubTime.setText(articlePreInfo.getPubtime().subSequence(5, 16));
        }
        TextView content = findViewById(R.id.w_art_content_text);
        if(articlePreInfo.getContent() != null){
            content.setText(articlePreInfo.getContent());
            /*content.setClickable(true);
            content.setOnClickListener(view -> {
                // 点击跳转详情页面
                gotoDetail();
            });*/
        }


        // 获取用户头像
        if(!(articlePreInfo.getHeadimg() == null || "".equals(articlePreInfo.getHeadimg()))){
            ResponseCallback callback = new ResponseCallback() {
                @Override
                public void onSuccess(Object res) {
                    byte[] image = (byte[]) res;
                    Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);  //使用BitmapFactory工厂，把字节数组转化为bitmap
                    userHeadImg.setImageBitmap(bitmap);
                }
                @Override
                public void onFailure(OkHttpException failuer) {
                    ThrowException.print(failuer, failuer.getEmsg());
                }
            };
            AsynRequestUtil.loadImg(AppServer.HEAD_IMG_PATH + articlePreInfo.getHeadimg(), null, callback);
        }else {
            userHeadImg.setImageResource(R.mipmap.user_head_img);
        }
        // 点击头像跳转用户
        userHeadImg.setClickable(true);
        userHeadImg.setOnClickListener(view -> {
            Intent intent = new Intent(context, UserDetailActivity.class);
            intent.putExtra("userId", articlePreInfo.getId());
            intent.putExtra("currUser", currUserID);
            context.startActivity(intent);
        });


        // 获取话题
        if(articlePreInfo.getHastopic() != 0){
            // TODO
        }else {
            // TODO 清空
        }

        // 获取图片
        if(articlePreInfo.getHaspic() != 0){
            RequestParams params = new RequestParams();
            params.put("artid", articlePreInfo.getUid());
            ResponseCallback callback = new ResponseCallback() {
                @Override
                public void onSuccess(Object res) {
                    try {
                        List<TArtPic> artPicList = JacksonUtil.json2list((String)res, TArtPic.class);
                        displayImage(artPicList);
                    } catch (Exception e) {
                        ThrowException.print(e);
                    }
                }
                @Override
                public void onFailure(OkHttpException failuer) {
                    ThrowException.print(failuer, failuer.getEmsg());
                }
            };
            AsynRequestUtil.post(AppServer.ROOT_PATH + "/article/getArtPic", params, null, callback);
        }else {
            displayImage(null);
        }

        // 点击删除
        /*QMUIRoundButton delete = findViewById(R.id.w_art_delete);
        delete.setOnClickListener(view -> {
            RequestParams params = new RequestParams();
            params.put("uid", articlePreInfo.getUid());
            AsynRequestUtil.post(AppServer.ROOT_PATH + "/manage/deleteArticle", params, null, null);
        });*/
    }

    /**
     * 点击跳转详情
     */
    /*private void gotoDetail(){
        // 添加浏览记录
        RequestParams params = new RequestParams();
        params.put("userid", currUserID);
        params.put("artid", articlePreInfo.getUid());
        AsynRequestUtil.post(AppServer.ROOT_PATH + "/article/addView", params, null, null);
        // 跳转详情页面
        Intent intent = new Intent(context, ArticleActivity.class);
        intent.putExtra("currUserId", currUserID);
        intent.putExtra("article", articlePreInfo);
        context.startActivity(intent);

    }*/


    /**
     * 展示图片
     */
    private void displayImage(List<TArtPic> artPics){
        imageLayout.removeAllViews();
        if(artPics == null){
            return;
        }
        int width = imageLayout.getWidth();
        int size = artPics.size();
        if(size == 1){
            imageWidth = width;
        }else if (size == 2 || size == 4){
            imageWidth = (width - 2) / 2;
        }else {
            imageWidth = (width -3) / 3;
        }
        for(int i = 0; i < size; i++){
            ResponseCallback callback = new ResponseCallback() {
                @Override
                public void onSuccess(Object res) {
                    byte[] image = (byte[]) res;
                    Bitmap bitmap = BitmapFactory.decodeByteArray(image, 0, image.length);  //使用BitmapFactory工厂，把字节数组转化为bitmap
                    ImageView imageView = new ImageView(context);
                    imageView.setImageBitmap(bitmap);
                    GridLayout.LayoutParams layoutParams = new GridLayout.LayoutParams();
                    layoutParams.width = imageWidth;
                    layoutParams.height = imageWidth;
                    imageView.setLayoutParams(layoutParams);
                    imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                    imageLayout.addView(imageView);
                }
                @Override
                public void onFailure(OkHttpException failuer) {
                    ThrowException.print(failuer, failuer.getEmsg());
                }
            };
            AsynRequestUtil.loadImg(AppServer.ARTICLE_IMG_PATH + artPics.get(i).getUid(), null, callback);
        }
    }

}
